import wsgiref.handlers
import sys
import os
import string
import codecs
import random
import re
import cgi
import datetime
import time
import math
import pickle
import logging
import urlparse
from dateutil import parser

DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
LIB_PATH = os.path.join(DIR_PATH, "lib")
EXTRA_PATHS = []
for path in os.listdir(LIB_PATH):
    fullpath = os.path.join(LIB_PATH, path)
    if os.path.isdir(fullpath) and not path.startswith("."):
        EXTRA_PATHS.append(fullpath)
sys.path = sys.path + EXTRA_PATHS

from google.appengine.api import mail
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import search
from google.appengine.ext import db
from google.appengine.api import images
from google.appengine.api import urlfetch
from datetime import datetime, timedelta
from django.core import serializers
from django.http import HttpResponsePermanentRedirect
from django.utils import simplejson as json
from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.api import images 
from google.appengine.ext.db import GqlQuery
from models import *
from utilities import *


webapp.template.register_template_library('customfilters')
webapp.template.register_template_library('smart_if')


# Set to true if we want to have our webapp print stack traces, etc
_DEBUG = True


class BaseRequestHandler(webapp.RequestHandler):
  """Supplies a common template generation function.

  When you call generate(), we augment the template variables supplied with
  the variables present in this function.
  """
  def generate(self, template_name, template_values={}):
    values = {
      'request': self.request,
      'application_name': 'Club de Fans de...',
    }
    values.update(template_values)
    directory = os.path.dirname(__file__)
    path = os.path.join(directory, os.path.join('admin', template_name))
    self.response.out.write(template.render(path, values, debug=_DEBUG))

    
class Index(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0
    template_values = {

    }
    self.generate('index.html', template_values)


class Songs(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0
      
    queryitems = Song.all()
    queryitems.order('pubDate')
    items = queryitems.fetch(500)

    template_values = {
      'songs': items
    }
    self.generate('songs.html', template_values)


class SongAction(BaseRequestHandler):
  def get(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if action == 'delete':
      item = Song.get(itemkey)
      item.delete()
      self.redirect("/admin/songs", False)
      return 1

    elif action=='edit':
      try:
        item = Song.get(itemkey)
      except:
        queryitem = Song.all()
        queryitem.filter(' songId = ', int(itemkey))
        items = queryitem.fetch(1)
        item = items[0]

      title = item.title
      url = item.url
      artistUrl = item.artistUrl
      artist = item.artist
      pubDate = item.pubDate
      key = str(item.key())

      template_values = {
        'itemkey': key,
        'title': title,
        'url': url,
        'pubDate': pubDate,
        'artistUrl': artistUrl,
        'artist': artist,
      }
    elif action=='new':
      template_values = {
      }
    self.generate("song.html", template_values)

  def post(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if itemkey != '':
      item = Song.get(itemkey)
      creating = False
    else:
      item = Song()
      creating = True

    if self.request.get("save")!='':
      if creating:
        # Get the latest orderNum used, increase it by 1 and use it
        queryitem = Song.all()
        queryitem.order('-songId')
        items = queryitem.fetch(1)

        if not len(items) > 0:
          lastId = 0
        else:
          lastId = items[0].songId
          
        songId = lastId + 1
        item.songId = songId
      
      item.title = self.request.get("title")
      item.url = self.request.get("url")
      item.artistUrl = self.request.get("artistUrl")
      item.artist = self.request.get("artist")
      pubDate = self.request.get('pubDate')
      if pubDate != '':
        item.pubDate = parser.parse(pubDate)
      else: 
        item.pubDate = ''
      item.put()

    self.redirect("/admin/songs", True)

class Kws(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    queryitems = Keyword.all()
    queryitems.order('pubDate')
    items = queryitems.fetch(500)

    template_values = {
      'kws': items
    }
    self.generate('kws.html', template_values)


class KwAction(BaseRequestHandler):
  def get(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0
    
    if action == 'delete':
      item = Keyword.get(itemkey)
      item.delete()
      self.redirect("/admin/kws", False)
      return 1

    elif action=='edit':
      item = Keyword.get(itemkey)

      key = str(item.key())

      template_values = {
        'itemkey': key,
        'kw': item,
      }
    elif action=='new':
      template_values = {
      }
    self.generate("kw.html", template_values)

  def post(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if itemkey != '':
      item = Keyword.get(itemkey)
      creating = False
    else:
      item = Keyword()
      creating = True

    if self.request.get("save")!='':

      item.word = self.request.get("word")
      item.slug = self.request.get("slug")
      pubDate = self.request.get('pubDate')
      if pubDate != '':
        item.pubDate = parser.parse(pubDate)
      else: 
        item.pubDate = ''
      item.put()

    self.redirect("/admin/kws", True)
    
class KwBulk(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    template_values = {
    }
    self.generate("bulk.html", template_values)

  def post(self, itemkey, action):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    if itemkey != '':
      item = Keyword.get(itemkey)
      creating = False
    else:
      item = Keyword()
      creating = True

    if self.request.get("save")!='':

      item.word = self.request.get("word")
      item.slug = self.request.get("slug")
      pubDate = self.request.get('pubDate')
      if pubDate != '':
        item.pubDate = parser.parse(pubDate)
      else: 
        item.pubDate = ''
      item.put()

    self.redirect("/admin/kws", True)

class Users(BaseRequestHandler):
  def get(self):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0
    template_values = {

    }
    self.generate('users.html', template_values)


class UploadImage(BaseRequestHandler):
  def get(self, filekey, callback):
    imagetype = self.request.get('imagetype')
    template_values = {
      'filekey': filekey,
      'callback': callback,
      'imagetype': imagetype
    }
    self.generate('fileupload.html', template_values)

  def post(self, filekey, callback):
    item = self.request.POST.get('fileupload')
    imagetype = self.request.get('imagetype')

    file_content = item.file.read()
    content = db.Blob(file_content)

    myfile = File()
    img = images.Image(content)
    myfile.bytes_content = content
    myfile.code= str(random.randint(10000000,99999999))
    myfile.mime = 'image/jpg'
    myfile.extension = 'jpg'
    myfile.size = 0
    myfile.height = img.height
    myfile.width = img.width
    myfile.imagetype = imagetype
    myfile.filekey = str(filekey)
    myfile.put()
    template_values = {
      'filekey': filekey,
      'imagekey': str(myfile.key()),
      'posted': True,
      'callback': callback,
      'imagetype': imagetype
    }
    self.generate('fileupload.html', template_values)


class DeleteImage(BaseRequestHandler):
  def post(self, key):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    if access==0:
      return 0

    myfile = File.get(key)
    myfile.delete()


# Create first admin user to start working with the app.
class PopulateUsers(BaseRequestHandler):
  def get(self):
    user = CustomUser(name="Admin",
              user=users.GetCurrentUser(),
              role="admin")
    user.put()


def main():
  application = webapp.WSGIApplication([
    ('/admin/populateusers/', PopulateUsers),
    ('/admin/upload/(.*)/(.*)/', UploadImage),
    ('/admin/image/delete/(.*)/', DeleteImage),
    ('/admin/songs', Songs),
    ('/admin/songs/(.*)/(new)/', SongAction),
    ('/admin/songs/(.*)/(save)/', SongAction),
    ('/admin/songs/(.*)/(delete)/', SongAction),
    ('/admin/songs/(.*)/(edit)/', SongAction),
    ('/admin/kws', Kws),
    ('/admin/kws/(.*)/(new)/', KwAction),
    ('/admin/kws/(.*)/(save)/', KwAction),
    ('/admin/kws/(.*)/(delete)/', KwAction),
    ('/admin/kws/(.*)/(edit)/', KwAction),
    ('/admin/kws/bulk/', KwBulk),
    ('/admin/', Index),
  ], debug=_DEBUG)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == "__main__":
  main()
